package com.vcc.web.core.component;


import com.vcc.core.exception.ProgramException;
import com.vcc.data.entity.Role;
import com.vcc.data.entity.User;
import com.vcc.service.service.UserService;
import com.vcc.web.core.util.UserUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class UserComponent {


    @Resource
    private UserService userService;

    public void verifyUserDataPermission(Long targetUserUserId) {
        Role loginRole = UserUtil.getRole();
        User loginUser = UserUtil.get();
        if (loginRole.getHasAllData()) {
            //获取卡片所属经销商
            long parentId = loginUser.getParentId() == null ? 0L : loginUser.getParentId();
            Long targetUserParentId = userService.getParentIdById(targetUserUserId);
            if (parentId != 0L) {
                //子账户
                //1. targetUserId 是否为自己
                //2. targetUserId 是否为自己的父级
                //3. targetUserId 的父级是否为自己的父级
                if (!Objects.equals(targetUserUserId, loginUser.getId()) && !Objects.equals(targetUserUserId, parentId) && !Objects.equals(parentId, targetUserParentId)) {
                    throw new ProgramException("非法操作");
                }
            } else {
                //主账户在操作
                //主账户时
                // 1. targetUserId 是否为自己
                // 2. targetUserId 的父级是否为自己
                if (!targetUserParentId.equals(loginUser.getId()) && !targetUserUserId.equals(loginUser.getId())) {
                    throw new ProgramException("非法操作");
                }
            }
        } else {
            if (!loginUser.getId().equals(targetUserUserId)) {
                throw new ProgramException("非法操作");
            }
        }
    }
}
